<template>
  <div ref="chartRef" class="pie-chart-container"></div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue'
import * as echarts from 'echarts'

const chartRef = ref(null)
let chartInstance = null

const getChartData = () => {
  return [
    { value: 1452, name: '文艺' },
    { value: 905, name: '经管/励志' },
    { value: 888, name: '人文社科' },
    { value: 1057, name: '生活' },
    { value: 429, name: '教育' },
    { value: 795, name: '科技' },
    { value: 437, name: '进口书' },
  ]
}

const initChart = () => {
  const data = getChartData()

  const option = {
    backgroundColor: '#fff',
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      top: '5%',
      left: 'center',
      textStyle: {
        color: '#666',
        fontSize: 12
      },
      data: data.map(item => item.name)
    },
    series: [
      {
        name: '图书分类',
        type: 'pie',
        radius: ['40%', '70%'],
        center: ['50%', '60%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 14,
            fontWeight: 'bold',
            formatter: '{b}\n{d}%'
          }
        },
        labelLine: {
          show: false
        },
        data: data,
        color: [
          '#409EFF', // 计算机 - 蓝色
          '#67C23A', // 文学 - 绿色
          '#E6A23C', // 历史 - 橙色
          '#F56C6C', // 经济 - 红色
          '#909399',  // 科学 - 灰色
          // 新增的颜色
          '#26A69A', // 青色
          '#4DB6AC'  // 蓝绿色
        ]
      }
    ]
  }

  chartInstance.setOption(option)
}

onMounted(() => {
  chartInstance = echarts.init(chartRef.value)
  initChart()
  window.addEventListener('resize', resizeChart)
})

onBeforeUnmount(() => {
  if (chartInstance) {
    chartInstance.dispose()
    chartInstance = null
  }
  window.removeEventListener('resize', resizeChart)
})

const resizeChart = () => {
  chartInstance?.resize()
}

defineExpose({
  resizeChart
})
</script>

<style scoped>
.pie-chart-container {
  width: 100%;
  height: 100%;
  min-height: 250px;
}
</style>